package com.example.demo.filter;

import com.example.demo.util.MayiktJwtUtils;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.www.BasicAuthenticationFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;
/**
 * Jwt验证授权拦截器
 *
 * */

public class JWTAuthorizationFilter extends BasicAuthenticationFilter {

    public JWTAuthorizationFilter(AuthenticationManager authenticationManager) {
        super(authenticationManager);
    }

    //拦截请求并验证token
    @Override
    protected void doFilterInternal(HttpServletRequest request,
                                    HttpServletResponse response,
                                    FilterChain chain) throws IOException, ServletException {

        //从请求头中获取token
        String tokenHeader = request.getHeader("token");
        // 如果请求头中有token，则进行解析，并且设置认证信息
        SecurityContextHolder.getContext().setAuthentication(
                //调用下面的验证token方法
                setAuthentication(tokenHeader));

        //放行该请求
        super.doFilterInternal(request, response, chain);
    }




    // 验证token，并且验证权限，返回一个
    private UsernamePasswordAuthenticationToken setAuthentication(String tokenHeader) {

        //调用这个方法，如果验签失败 说明伪造了或被篡改了jwt（密钥放在服务器端）
        //验签成功就会返回一个name ，失败不会返回
        String username = MayiktJwtUtils.getUsername(tokenHeader);
        if (username != null) {
            //验签成功
            //解析用户权限列表
            List<SimpleGrantedAuthority> userRoles = MayiktJwtUtils.getUserRole(tokenHeader);


            UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(username, null, userRoles);
            System.out.println(token);
            return token;
        }
        return null;
    }
}
